package com.diipo.weibo;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.LinkedList;
import com.diipo.weibo.adapter.MsgItemAdapter;
import com.diipo.weibo.entity.Msg;
import com.diipo.weibo.utils.HttpUtils;
import com.diipo.weibo.utils.JsonUtils;
import com.google.gson.reflect.TypeToken;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

public class MsgActivity extends Activity{
	private String TAG = MsgActivity.class.getSimpleName();
	private ListView msgListView;
	private MsgItemAdapter mAdapter;
	private Button mbtnUnRead;
	private Button mbtnRead;
	private SharedPreferences mPrefs;
	private LinkedList<Msg> mUnReadList = new LinkedList<Msg>();
	private LinkedList<Msg> mReadList = new LinkedList<Msg>();
//	private LinkedList<Msg> list = new LinkedList<Msg>();
	private LinkedList<Msg> list2 = new LinkedList<Msg>();
	
	
	private String mUrl_unread = "/api/notifications/inbox.json?api_key=";//未查看
	private String mUrl_read = "/api/notifications/viewed.json?api_key="; //已经查看
	private Context mctx;
	private boolean mboolRead;
	private boolean mboolUnRead;
	private boolean mFlag; //switch the read & unread btn
	
	private Button mRefreshMsg;
	private TextView mMore;
	private String mId;   //for more msg recored
	private boolean readMore = true;
	private boolean unreadMore = true;
	
	private Handler handler = new Handler();
	private boolean mIsmore = false;
	private int moreCount = 0;
	
	private String mResponseCode = "0";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// Hide title 
        requestWindowFeature( Window.FEATURE_NO_TITLE );
		setContentView(R.layout.message_view);
		mboolUnRead = true;
		mboolRead = false;
		mFlag = false;//
		Log.e(TAG, " MsgActivity onCreate() called ...");
		mctx = this;
//		ConfigInfo.setInstanceContext(this);
		mPrefs = getSharedPreferences(ConfigInfo.USER_PREFERENCES,MODE_PRIVATE);
		mRefreshMsg = (Button) findViewById(R.id.titlebar_refresh);
		mRefreshMsg.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.e(TAG, " onClick() called ,pyb mRefreshWeibo.setEnabled(false).");
//				mRefreshMsg.setEnabled(false);
				if(mboolUnRead){// un read msg
//					mId = mUnReadList.get(mUnReadList.size()-1).getId();
//					Log.e(TAG, " add more unread data from the server pos = " + mUnReadList.size() + ",the last id = " + mId);
//					new AsyncDataLoader(asyncRemoteCallback,mctx,mUrl_unread,"","",mId).execute();
					Log.e(TAG, " refresh data from server,get the newest data of the un read msg.........");
//					mUnReadList.clear();
					//update the msgActivity UI
					new AsyncDataLoader(asyncRemoteCallback,mctx,mUrl_unread,"","","").execute();
				}else{
//					mId = mReadList.get(mReadList.size()-1).getId();
//					Log.e(TAG, " add more read data from the server pos = " + mReadList.size() + ",the last id = " + mId);
//					new AsyncDataLoader(asyncRemoteCallback,mctx,mUrl_read,"","",mId).execute();
					
					Log.e(TAG, " refresh data from server,get the newest data of the read msg.........");
//					mReadList.clear();
					//update the msgActivity UI
					new AsyncDataLoader(asyncRemoteCallback,mctx,mUrl_read,"","","").execute();
				}
//				String before = list.get(list.size()-1).getCreated_time();
//				Log.e(TAG, " add more data from the server last before time = " + before);
//				new AsyncDataLoader(asyncRemoteCallback,mctx,url_activity,"","",before).execute();
			}
		});
		LinearLayout v = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.list_footer, null);
		mMore = (TextView)v.findViewById(R.id.footer_more);
		mMore.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Log.e(TAG, " add more data was click here...... ");
				// TODO Auto-generated method stub
				if(mboolUnRead){// un read msg
					try{
						mId = mUnReadList.get(mUnReadList.size()-1).getId();
					}catch(Exception e){
						Log.e(TAG, " Exception happend here,what's wrong?Baby?" );
						e.printStackTrace();
					}
					Log.e(TAG, " add more unread data from the server pos = " + mUnReadList.size() + ",the last id = " + mId);
					new AsyncDataLoader(asyncRemoteCallback,mctx,mUrl_unread,"","",mId).execute();
				}else{
					try{
						mId = mReadList.get(mReadList.size()-1).getId();
					}catch(Exception e){
						Log.e(TAG, " Exception happend here,what's wrong?Baby?" );
						e.printStackTrace();
					}
					Log.e(TAG, " add more read data from the server pos = " + mReadList.size() + ",the last id = " + mId);
					new AsyncDataLoader(asyncRemoteCallback,mctx,mUrl_read,"","",mId).execute();
				}
				mIsmore = true;
			}
		});
		msgListView = (ListView) findViewById(R.id.msg_listview);
		msgListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Log.e(TAG, " MsgActivity onItemClick() called ...position = " + position);
				Intent intent = new Intent(MsgActivity.this,WeiboDetailsActivity.class);
				if(mboolUnRead){
					try{
						intent.putExtra(ConfigInfo.COMM.MSG_ID, mUnReadList.get(position).getSource().getId());
						intent.putExtra(ConfigInfo.COMM.NOTIFY_ID, mUnReadList.get(position).getId());
						//remove the unread msg from the mUnReadList
						mUnReadList.remove(position);
					}catch(Exception e){
						Log.e(TAG, " Exception happend here,what's wrong?Baby?" );
						e.printStackTrace();
					}
					ConfigInfo.IS_UN_READ_VIEW = true;
				}else{
					try{
						intent.putExtra(ConfigInfo.COMM.MSG_ID, mReadList.get(position).getSource().getId());
					}catch(Exception e){
						Log.e(TAG, " Exception happend here,what's wrong?Baby?" );
						e.printStackTrace();
					}
				}
				intent.putExtra(ConfigInfo.COMM.ITEM_TYPE, "");  
				startActivity(intent);
			}
			
		});
		msgListView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				if(scrollState == SCROLL_STATE_FLING){
					Log.e(TAG, " SCROLL_STATE_FLING mRefreshWeibo.setEnabled(false).");
					mRefreshMsg.setEnabled(false);
				}else if(scrollState == SCROLL_STATE_IDLE){
//					handler.postDelayed(new Runnable() {
//						@Override
//						public void run() {
//							mRefreshMsg.setEnabled(true);
//						}
//					},2000);
					Log.e(TAG, " SCROLL_STATE_IDLE mRefreshWeibo.setEnabled(true).");
					mRefreshMsg.setEnabled(true);
				}else if(scrollState == SCROLL_STATE_TOUCH_SCROLL){
//					Log.e(TAG, " SCROLL_STATE_TOUCH_SCROLL mRefreshWeibo.setEnabled(false).");
					mRefreshMsg.setEnabled(false);
				}else{
					
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				
			}
		});
		msgListView.addFooterView(v);
		mbtnUnRead = (Button) findViewById(R.id.unread_btn);
		mbtnRead = (Button) findViewById(R.id.read_btn);
		
		mbtnUnRead.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.e("pyb"," unread Button was click");
				mbtnUnRead.setBackgroundResource(R.drawable.read_msg_selected);
				mbtnRead.setBackgroundResource(R.drawable.read_msg_normal);
				mboolUnRead = true;
				if(mboolUnRead ){
					mboolRead = false;
//					MsgItemAdapter adapter = new MsgItemAdapter(mUnReadList,MsgActivity.this);
//					msgListView.setAdapter(adapter);
					mAdapter = new MsgItemAdapter(mUnReadList,MsgActivity.this);
					msgListView.setAdapter(mAdapter);
					//if(mUnReadList.size() == 0){
					if(!unreadMore){
						Log.e(TAG,"unreadMore:false==============nomore data");
						Log.i(TAG, " mMore.setVisibility(false).196");
						mMore.setVisibility(View.GONE);
					}else{
						Log.i(TAG, " mMore.setVisibility(true).199");
						if(mReadList.size()< 20 || mUnReadList.size() < 20){
							mMore.setVisibility(View.GONE);
						}else{
						Log.i(TAG, " mMore.setVisibility(true).228");
						mMore.setVisibility(View.VISIBLE);
						}
					}
					return;
				}
				new AsyncDataLoader(asyncRemoteCallback,mctx,mUrl_unread,"","","").execute();
				mFlag = false;
			}
		});
		
		mbtnRead.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.e("pyb"," read RadioButton was click");
				mbtnUnRead.setBackgroundResource(R.drawable.read_msg_normal);
				mbtnRead.setBackgroundResource(R.drawable.read_msg_selected);
				mboolRead = true;
				if(mboolRead&& mFlag){
					mboolUnRead = false;
					mAdapter = new MsgItemAdapter(mReadList,MsgActivity.this);
					msgListView.setAdapter(mAdapter);
					//if(mReadList.size() == 0){
					if(!readMore){
						Log.i(TAG, " mMore.setVisibility(false).224");
						mMore.setVisibility(View.GONE);
					}else{
						if(mReadList.size()< 20 || mUnReadList.size() < 20){
							mMore.setVisibility(View.GONE);
						}else{
						Log.i(TAG, " mMore.setVisibility(true).228");
						mMore.setVisibility(View.VISIBLE);
						}
					}
					return;
				}
				new AsyncDataLoader(asyncRemoteCallback,mctx,mUrl_read,"","","").execute();
				mFlag = true;
				mboolUnRead = false;
			}
		});
		new AsyncDataLoader(asyncRemoteCallback,this,mUrl_unread,"","","").execute();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.e(TAG," Msg onResume() called....");
		if(ConfigInfo.IS_UN_READ_VIEW){
			//update the unread msg UI here
			ConfigInfo.IS_UN_READ_VIEW = false;
			if(mboolUnRead){
				mAdapter = new MsgItemAdapter(mUnReadList,MsgActivity.this);
			}else{
				mAdapter = new MsgItemAdapter(mReadList,MsgActivity.this);
			}
			msgListView.setAdapter(mAdapter);
		}
		
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		Log.e(TAG," Msg onStop() called....");
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.e(TAG," Msg onDestroy() called....");
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {// 捕捉返回键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			ConfirmExit();// 按了返回键，但已经不能返回，则执行退出确认
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void ConfirmExit() {// 退出确认
		AlertDialog.Builder dialog = new AlertDialog.Builder(MsgActivity.this);
		dialog.setTitle(mctx.getString(R.string.exit));
		dialog.setMessage(mctx.getString(R.string.is_exit_weibo));
		dialog.setPositiveButton(mctx.getString(R.string.btn_ok), new DialogInterface.OnClickListener() {// 退出按钮
					@Override
					public void onClick(DialogInterface dialog, int i) {
						// TODO Auto-generated method stub
						MsgActivity.this.finish();// 关闭activity
						android.os.Process.killProcess(android.os.Process.myPid());
					}
				});
		dialog.setNegativeButton(mctx.getString(R.string.btn_cancle), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int i) {
				// 不退出不用执行任何操作
			}
		});
		dialog.show();// 显示对话框
	}
	
	/**
	 * 异步加载服务器上的微博数据的监听器,已查看和未查看 消息
	 */
	private AsyncDataLoader.Callback asyncRemoteCallback = new AsyncDataLoader.Callback() {
		
	 
		private Type listType = new TypeToken<LinkedList<Msg>>() {}.getType();
		private String result;
		@Override
		public void onStart(String address, String id) {
			Log.i(TAG,"asyncRemoteCallback ............... address:"+address);
			// mPrefs =
			// getSharedPreferences(ConfigInfo.USER_PREFERENCES,MODE_PRIVATE);
			StringBuffer url = new StringBuffer();
			url.append(mPrefs.getString(ConfigInfo.PREF_SERVER_ADDRESS, mPrefs
					.getString(ConfigInfo.PREF_SERVER_ADDRESS,
							ConfigInfo.COMM.CONST_SERVER_ADDRESS)));
			url.append(address);
			url.append(ConfigInfo.COMM.APY_KEY);
			if(mboolUnRead){//未查看
				if (mUnReadList.size()>=20) {
					url.append("&max_id=");
					url.append(id);
				}
			}else{
				if (mReadList.size()>=20) {
					url.append("&max_id=");
					url.append(id);
				}
			}
			String username = mPrefs.getString(ConfigInfo.PREF_USERNAME, "");
			String passwd = mPrefs.getString(ConfigInfo.PREF_PASSWORD, "");

			// 需要做出判断，username 或者 passwd为非法值

			result = HttpUtils.doPost(url.toString(), username, passwd,null);
			Log.i("", "//////////////////msg url address = " + url);
			// Log.e(""," username  = "+username);
			// Log.e(""," passwd  = "+passwd);
			Log.e("", " msg result =  " + result);
			if (result != ConfigInfo.HTTPRETURN.COMMHTTPERRORS
					&& result != ConfigInfo.HTTPRETURN.HTTP_ERROR_400
					&& result != ConfigInfo.HTTPRETURN.HTTP_ERROR_401
					&& result != ConfigInfo.HTTPRETURN.HTTP_ERROR_CODE_404
					&& result != ConfigInfo.HTTPRETURN.HTTPERROR) {
				if (mboolUnRead) {
					// 大于20加载更多
					Log.e(TAG," load the unread msg from the server");
					if (mUnReadList.size() >= 20) {
						list2 = JsonUtils.parseUserFromJsons(result, listType);
						moreCount = list2.size();
						
						Iterator<Msg> iterator = list2.iterator();
						while (iterator.hasNext()) {
							mUnReadList.add(iterator.next());
						}
						// hide the more btn data from the server
						if(list2.size() < 20){
							//hanlder在主线程做UI操作
							handler.post(new Runnable() {
								@Override
								public void run() {
									Log.i(TAG, " mMore.setVisibility(false).362");
									mMore.setVisibility(View.GONE);
									unreadMore = false;
								}
							});
						}else{
							handler.postDelayed(new Runnable() {
								@Override
								public void run() {
									mMore.setVisibility(View.VISIBLE);
									Log.i(TAG, " mMore.setVisibility(true).372");
									unreadMore = true;
								}
							},1000);
						}
						//clear the list2 here
						list2.clear();
					} else {
						mUnReadList.clear();
						mUnReadList = JsonUtils.parseUserFromJsons(result,listType);
						if(mUnReadList.size()< 20){
							handler.post(new Runnable() {
								@Override
								public void run() {
									Log.i(TAG, " mMore.setVisibility(false).376");
									mMore.setVisibility(View.GONE);
									unreadMore = false;
								}
							});
						}else{
							//mUnReadList.size() >= 20
							handler.postDelayed(new Runnable() {
								@Override
								public void run() {
									Log.i(TAG, " mMore.setVisibility(true).386");
									mMore.setVisibility(View.VISIBLE);
									unreadMore = true;
								}
							},1000);
						}
					}
				}else{
					Log.e(TAG," load the read msg from the server  ==============================   read");
					// 大于20加载更多
					if (mReadList.size() >= 20) {
						list2 = JsonUtils.parseUserFromJsons(result, listType);
						moreCount = list2.size();
						Iterator<Msg> iterator = list2.iterator();
						while (iterator.hasNext()) {
							mReadList.add(iterator.next());
						}
						// hide the more btn data from the server
						if(list2.size() < 20){
							//hanlder在主线程做UI操作
							handler.post(new Runnable() {
								@Override
								public void run() {
									Log.i(TAG, " mMore.setVisibility(false).405");
									mMore.setVisibility(View.GONE);
									readMore = false;
								}
							});
						}else{
							//mUnReadList.size() >= 20
							handler.postDelayed(new Runnable() {
								@Override
								public void run() {
									Log.i(TAG, " mMore.setVisibility(true).386");
									mMore.setVisibility(View.VISIBLE);
									readMore = true;
								}
							},1000);
						}
						//clear the list2 here
						list2.clear();
					} else {
						mReadList.clear();
						mReadList = JsonUtils.parseUserFromJsons(result,listType);
						if(mReadList.size()< 20){
							handler.post(new Runnable() {
								@Override
								public void run() {
									Log.i(TAG, " mMore.setVisibility(false).418");
									mMore.setVisibility(View.GONE);
									readMore = false;
								}
							});
						}else{
							handler.postDelayed(new Runnable() {
								@Override
								public void run() {
									Log.i(TAG, " mMore.setVisibility(true).427");
									mMore.setVisibility(View.VISIBLE);
									readMore = true;
								}
							},1000);
						}
					}
				}
			} else if(result == ConfigInfo.HTTPRETURN.HTTP_ERROR_CODE_404){
				Log.e(TAG, " no data:404===========================================  ");
				mResponseCode = "404";
				//Toast.makeText(MsgActivity.this, ConfigInfo.HTTPRETURN.HTTPERROR, Toast.LENGTH_LONG).show();
				//mMore.setVisibility(View.GONE);
				handler.post(new Runnable() {
					@Override
					public void run() {
						mMore.setVisibility(View.GONE);
						//Toast.makeText(MsgActivity.this, ConfigInfo.HTTPRETURN.HTTP_ERROR_404, Toast.LENGTH_LONG).show();
						Log.i(TAG, " mMore.setVisibility(false).429");
					}
				});				
				if(mboolUnRead)
					unreadMore = false;
				else
					readMore = false;;
			}else{
				
			}
		}

		@Override
		public void onFinish() {
			/*if(!msgListView.isFocusable()){
				Log.e(TAG, " no data===========================================  ");
				Toast.makeText(MsgActivity.this, ConfigInfo.HTTPRETURN.HTTPERROR, Toast.LENGTH_LONG).show();
				return;
			}*/
//			MsgItemAdapter adapter = null;
			if (result == ConfigInfo.HTTPRETURN.COMMHTTPERRORS
					|| result == ConfigInfo.HTTPRETURN.HTTP_ERROR_400
					|| result == ConfigInfo.HTTPRETURN.HTTP_ERROR_401
					|| result == ConfigInfo.HTTPRETURN.HTTPERROR
					|| result == ConfigInfo.HTTPRETURN.HTTP_ERROR_CODE_404){
				Toast.makeText(MsgActivity.this, 
						result.equals("404")?mctx.getString(R.string.no_viewed_notification):result, Toast.LENGTH_LONG).show();
				if(mReadList.size()< 20 || mUnReadList.size() < 20){
					mMore.setVisibility(View.GONE);
				}
				Log.e(TAG, " mReadList.size() = " + mReadList.size() + " , mUnReadList.size() = " + mUnReadList.size());
				if(mboolUnRead){
					mAdapter = new MsgItemAdapter(mUnReadList,MsgActivity.this);
					msgListView.setAdapter(mAdapter);
				}else{
					mAdapter = new MsgItemAdapter(mReadList,MsgActivity.this);
					msgListView.setAdapter(mAdapter);
				}
				return;
			}
			if(mboolUnRead){
				if(mUnReadList.size() < 20){
					Log.i(TAG, " mMore.setVisibility(false).459");
					mMore.setVisibility(View.GONE);
					unreadMore = false;
				}
				if(mUnReadList.size() < 1){
					Log.e(TAG, " no data===========================================  ");
					Toast.makeText(MsgActivity.this, mResponseCode.equals("404")?mctx.getString(R.string.no_new_notification):ConfigInfo.HTTPRETURN.HTTPERROR, Toast.LENGTH_LONG).show();
					//return;
				}
				mAdapter = new MsgItemAdapter(mUnReadList,MsgActivity.this);
				msgListView.setAdapter(mAdapter);
				if(mIsmore){
					Log.e(TAG, " mIsmore = true, mUnReadList.size() = " + mUnReadList.size());
					msgListView.setSelection(mUnReadList.size()-1-moreCount);
					mIsmore = false;
				}
			}else{
				if(mReadList.size() < 20){
					Log.i(TAG, " mMore.setVisibility(false).477");
					mMore.setVisibility(View.GONE);
					readMore = false;
				}
				if(mReadList.size() < 1){
					Log.e(TAG, " no data===========================================  ");
					Toast.makeText(MsgActivity.this, mResponseCode.equals("404")?mctx.getString(R.string.no_viewed_notification):ConfigInfo.HTTPRETURN.HTTPERROR, Toast.LENGTH_LONG).show();
					//return;
				}
				mAdapter = new MsgItemAdapter(mReadList,MsgActivity.this);
				msgListView.setAdapter(mAdapter);
				if(mIsmore){
					Log.e(TAG, " mIsmore = true, mReadList.size() = " + mReadList.size());
					msgListView.setSelection(mReadList.size()-1-moreCount);
					mIsmore = false;
				}
			}
		}

		@Override
		public void onPrepare() {
		}
		@Override
		public void onStart(String address, String arg1, String arg2) {
			// TODO Auto-generated method stub
			
		}
	};
}
